package com.yanzhu.api;

import com.alibaba.fastjson.JSON;
import com.yanzhu.bean.ResponseBean;
import com.yanzhu.constant.Constant;
import com.yanzhu.service.MaterialService;
import com.yanzhu.service.TempletService;
import com.yanzhu.service.VideoService;
import com.yanzhu.service.model.Material;
import com.yanzhu.service.model.Templet;
import com.yanzhu.service.model.Video;
import com.yanzhu.util.CommonUtil;
import lombok.AllArgsConstructor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * @Author: 方炎柱
 * @Description: 上传视频
 * @Date: Created in 22:06 2018/1/17
 * @Modified:
 */
@AllArgsConstructor
@RestController
public class FileUploadAPI {

    private VideoService videoService;

    private TempletService templetService;

    private MaterialService materialService;

    private static Logger logger = LoggerFactory.getLogger(FileUploadAPI.class);

    /**
     * 上传视频
     */
    @RequestMapping("/uploadVideo")
    public ResponseBean uploadVideo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String uid = request.getParameter("uid");
        logger.info(uid + "");
        if (uid == null || uid.equals(""))
            return ResponseBean.fail("缺少用户ID");
        String duration = request.getParameter("duration");
        if (duration == null || duration.equals(""))
            return ResponseBean.fail("缺少视频时长");

        String tid = request.getParameter("tid");
        if (tid == null || tid.equals(""))
            return ResponseBean.fail("缺少模版id");

        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

        String filePath = "/home/hkserver/javaWeb/wechatvideo/video/";
        String visitPath = "https://wx.yangbingtech.com/";
        Random random = new Random();
        String intPath1 = random.nextInt(1000) + "/";
        String intPath2 = random.nextInt(1000) + "/";
        filePath = filePath + intPath1 + intPath2;

        visitPath = visitPath + intPath1 + intPath2;

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    logger.info("file name " + file.getOriginalFilename());
                    String filename = file.getOriginalFilename();
                    filename = CommonUtil.getMD5(filename.substring(0,filename.lastIndexOf("."))) + "." + filename.substring(filename.lastIndexOf("."));
                    uploadFile(file.getBytes(), filePath, filename);

                    Video video = new Video();
                    video.setUid(Long.parseLong(uid));
                    video.setDuration(Float.parseFloat(duration));
                    video.setPath(visitPath + filename);
                    //TODO
                    video.setImage_path(visitPath + "test.jpg");
                    video.setVideo_time((int) (new Date().getTime() / 1000));
                    video.setTid(Long.parseLong(tid));
                    if (videoService.insert(video) < 1)
                        return ResponseBean.fail("数据库错误!");
                    else
                        return ResponseBean.ok(video);

                } catch (Exception e) {
                    return ResponseBean.fail("上传失败," + e.getMessage());
                }
            } else {
                logger.error("the file is empty");
            }
        }

        return ResponseBean.fail("上传失败，因为文件是空的!.");

    }

    @RequestMapping("/uploadVideoPicture")
    public ResponseBean uploadVideoPicture(HttpServletRequest request) throws Exception {
        String vid = request.getParameter("vid");
        logger.info(vid + "");
        if (vid == null || vid.equals(""))
            return ResponseBean.fail("缺少视频ID");
        Video video = videoService.selectById(Long.parseLong(vid));
        if(video == null)
            return ResponseBean.fail("视频记录不存在！");

        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = "/home/hkserver/javaWeb/wechatvideo/video/picture/";
        String visitPath = "https://wx.yangbingtech.com/picture/";

        Random random = new Random();
        String intPath1 = random.nextInt(1000) + "/";
        String intPath2 = random.nextInt(1000) + "/";
        filePath = filePath + intPath1 + intPath2;
        visitPath = visitPath + intPath1 + intPath2;

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    logger.info("file name " + file.getOriginalFilename());
                    String filename = file.getOriginalFilename();
                    filename = CommonUtil.getMD5(filename.substring(0,filename.lastIndexOf("."))) + "." + filename.substring(filename.lastIndexOf("."));
                    uploadFile(file.getBytes(), filePath, filename);
                    video.setImage_path(visitPath + filename);

                    videoService.updateVideo(video);
                    return ResponseBean.ok(video);

                } catch (Exception e) {
                    return ResponseBean.fail("上传失败," + e.getMessage());
                }
            } else {
                logger.error("the file is empty");
            }
        }

        return ResponseBean.fail("上传失败，因为文件是空的!.");

    }

//    @RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
//    public ResponseBean uploadVideo(HttpServletRequest request) {
//        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
//
//        if (!file.isEmpty()) {
//            String uid = request.getParameter("uid");
//            if (uid == null || uid.equals(""))
//                return ResponseBean.fail("缺少用户ID");
//            String path = "upload/" + uid + "/";
//            String filePath = path + file.getOriginalFilename();
//
//            try {
//                // 这里只是简单例子，文件直接输出到项目路径下。
//                // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
//                // 还有关于文件格式限制、文件大小限制，详见：中配置。
//                BufferedOutputStream out = new BufferedOutputStream(
//                        new FileOutputStream(new File(filePath)));
//                out.write(file.getBytes());
//                out.flush();
//                out.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//                return ResponseBean.fail("上传失败," + e.getMessage());
//            }
//
//            Video video = new Video();
//            video.setUid(Long.parseLong(uid));
//            video.setPath(filePath);
//            video.setVideo_time((int) (new Date().getTime() / 1000));
//            if (videoService.insert(video) < 0)
//                return ResponseBean.fail("数据库错误!");
//            return ResponseBean.ok();
//        } else {
//            return ResponseBean.fail("上传失败，因为文件是空的!.");
//        }
//    }


    @RequestMapping(value = "/uploadTemplet")
    public ResponseBean uploadTemplet(HttpServletRequest request) {
        String name = request.getParameter("name");
        logger.info(name + "");
        if (name == null || name.equals(""))
            return ResponseBean.fail("缺少模版名称！");

        String type = request.getParameter("type");
        logger.info(type + "");
        if (type == null || type.equals(""))
            return ResponseBean.fail("缺少模版类型！");

        Templet templet = new Templet();
        templet.setName(name);
        templet.setType(Integer.parseInt(type));

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = "/home/hkserver/javaWeb/wechatvideo/video/templet/";
        String visitPath = "https://wx.yangbingtech.com/templet/";

        Random random = new Random();
        String intPath1 = random.nextInt(1000) + "/";
        String intPath2 = random.nextInt(1000) + "/";
        filePath = filePath + intPath1 + intPath2;
        visitPath = visitPath + intPath1 + intPath2;

        MultipartFile file = null;

        if(files.size() != 3)
            return ResponseBean.fail("缺少文件！");
        else {
            for (int i = 0; i < files.size(); ++i) {
                file = files.get(i);
                if (!file.isEmpty()) {
                    logger.info("file name " + file.getOriginalFilename());
                    try {
                        String filename = file.getOriginalFilename();
                        filename = CommonUtil.getMD5(filename.substring(0,filename.lastIndexOf("."))) + filename.substring(filename.lastIndexOf("."));
                        uploadFile(file.getBytes(), filePath, filename);
                        if (i == 0) {
                            templet.setCovers(visitPath + filename);
                        } else if (i == 1) {
                            templet.setMusic(visitPath + filename);
                        } else {
                            templet.setVideo(visitPath + filename);
                        }

                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        if (i == 0) {
                            return ResponseBean.fail("失败上传封面！");
                        } else if (i == 1) {
                            return ResponseBean.fail("失败上传背景音乐！");
                        } else {
                            return ResponseBean.fail("失败上传视频！");
                        }
                    }
                } else {
                    if (i == 0) {
                        return ResponseBean.fail("封面为空！");
                    } else if (i == 1) {
                        return ResponseBean.fail("背景音乐为空！");
                    } else {
                        return ResponseBean.fail("视频为空！");
                    }
                }
            }
            if (templetService.insert(templet) < 1)
                return ResponseBean.fail("数据库错误!");
            else
                return ResponseBean.ok(templet);
        }
    }

    @RequestMapping("/uploadMaterial")
    public ResponseBean uploadMaterial(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String tid = request.getParameter("tid");
        logger.info(tid + "");
        if (tid == null || tid.equals(""))
            return ResponseBean.fail("缺少模版ID！");

        String duration = request.getParameter("duration");
        if (duration == null || duration.equals(""))
            return ResponseBean.fail("缺少时长！");

        String is_loop = request.getParameter("is_loop");
        if (is_loop == null || is_loop.equals(""))
            return ResponseBean.fail("缺少是否循环！");

        String start_time = request.getParameter("start_time");
        if (start_time == null || start_time.equals(""))
            return ResponseBean.fail("缺少开始时间！");

        String width = request.getParameter("width");
        if (width == null || width.equals(""))
            return ResponseBean.fail("缺少宽度！");

        String height = request.getParameter("height");
        if (height == null || height.equals(""))
            return ResponseBean.fail("缺少高度！");

        String frame_sum = request.getParameter("frame_sum");
        if (frame_sum == null || frame_sum.equals(""))
            return ResponseBean.fail("缺少帧数！");

        String l_percent = request.getParameter("l_percent");
        if (l_percent == null || l_percent.equals(""))
            return ResponseBean.fail("缺少左坐标百分比！");

        String u_percent = request.getParameter("u_percent");
        if (u_percent == null || u_percent.equals(""))
            return ResponseBean.fail("缺少上坐标百分比！");

        String z_index = request.getParameter("z_index");
        if (z_index == null || z_index.equals(""))
            return ResponseBean.fail("缺少层次！");

        String ani_type = request.getParameter("ani_type");


        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

        String filePath = "/home/hkserver/javaWeb/wechatvideo/video/material/";
        String visitPath = "https://wx.yangbingtech.com/material/";

        Random random = new Random();
        String intPath1 = random.nextInt(1000) + "/";
        String intPath2 = random.nextInt(1000) + "/";
        filePath = filePath + intPath1 + intPath2;
        visitPath = visitPath + intPath1 + intPath2;

        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                try {
                    logger.info("file name " + file.getOriginalFilename());
                    String filename = file.getOriginalFilename();
                    filename = CommonUtil.getMD5(filename.substring(0,filename.lastIndexOf("."))) + "." + filename.substring(filename.lastIndexOf("."));
                    uploadFile(file.getBytes(), filePath, filename);

                    Material material = new Material();
                    material.setTid(Long.parseLong(tid));
                    material.setDuration(Float.parseFloat(duration));
                    material.setIs_loop(Integer.parseInt(is_loop));
                    material.setStart_time(Float.parseFloat(start_time));
                    material.setWidth(Integer.parseInt(width));
                    material.setHeight(Integer.parseInt(height));
                    material.setFrame_sum(Integer.parseInt(frame_sum));
                    material.setL_percent(Integer.parseInt(l_percent));
                    material.setU_percent(Integer.parseInt(u_percent));
                    material.setPicture_path(visitPath + filename);
                    material.setZ_index(Integer.parseInt(z_index));
                    if (!(ani_type == null || ani_type.equals("")))
                        material.setAni_type(Integer.parseInt(ani_type));
                    if (materialService.insert(material) < 1)
                        return ResponseBean.fail("数据库错误!");
                    else
                        return ResponseBean.ok(material);
                } catch (Exception e) {
                    return ResponseBean.fail("上传失败," + e.getMessage());
                }
            } else {
                logger.error("the file is empty");
            }
        }

        return ResponseBean.fail("上传失败，因为文件是空的!.");

    }

    /**
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     */
    @RequestMapping(value = "/upload/batch")
    public String batchUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => " + e.getMessage();
                }
            } else {
                return "You failed to upload " + i + " because the file was empty.";
            }
        }
        return "upload successful";
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()) targetFile.mkdirs();

        BufferedOutputStream stream = null;
        stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+fileName)));
        stream.write(file);
        stream.close();
    }

    @RequestMapping(value = "/showVideo")
    public void showVideo(HttpServletRequest request, HttpServletResponse response) {
        logger.info("showVideo");
        try {
//            System.out.println("-------------------------------下载版本文件对应设备类型id=" + vid + "------------------------------------");
//            String filePath = videoService.selectVideoPathById(vid);
//            if(filePath == null)
//                throw new Exception("文件不存在");
//            String[] fp = filePath.split("\\\\");
//            String fileName = fp[fp.length - 1];// 文件名称
//            System.out.println("-------------------------------上传文件名为=" + fileName);

            //下载机器码文件
//            response.setHeader("conent-type", "application/octet-stream");
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("ISO-8859-1"), "UTF-8"));
            String filePath = request.getParameter("filePath");
            if (filePath == null || filePath.equals(""))
                throw new Exception("文件路径不能为空！");

            OutputStream os = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);

            InputStream is = null;

            is = new FileInputStream(filePath);
            BufferedInputStream bis = new BufferedInputStream(is);

            int length = 0;
            byte[] temp = new byte[1 * 1024 * 10];

            while ((length = bis.read(temp)) != -1) {
                bos.write(temp, 0, length);
            }
            bos.flush();
            bis.close();
            bos.close();
            is.close();
        } catch (Exception e) {
            logger.error("Exception:" + e);
            e.printStackTrace();
        }
    }
}